var refreshGirdData; // 更新数据

var companyId = '';
var departmentName = '';
var alreadyformat = false;
var userdefault = {};
var params = {};

var headerCols = [];
var selectColumns = '';

var bootstrap = function ($, learun) {

    var pageWidth = 1024;
    var colNames = [];
    var colData2 = [];

    "use strict";
    var page = {
        init: function () {
            userdefault = learun.clientdata.get(['usersetting']);
            pageWidth = ($('.lr-layout-grid').width());

            page.bind();
        },
        bind: function () {
            // 搜索框初始化
            $('#txt_Keyword').on("keypress", function (e) {
                if (event.keyCode == "13") {
                    var $this = $(this);
                    var keyword = $this.val();
                    page.search({keyword: keyword});
                }
            });
            var myDate = new Date;
            var year = myDate.getFullYear(); //获取当前年
            var mon = myDate.getMonth() + 1; //获取当前月
            $("#monthStart").val(year + "-" + (mon < 10 ? "0" : "") + mon);
            $("#monthEnd").val(year + "-" + (mon < 10 ? "0" : "") + mon);
            $('#company_select').lrselect({
                type: 'tree',
                // placeholder: '请选择机构',
                height: 300,
                maxHeight: 300,
                // 是否允许搜索
                //allowSearch: true,
                select: function (item) {
                    if (item && item.value != '-1') {
                        companyId = item.value;

                        $('#departmentName').lrselectRefresh({
                            // 访问数据接口地址
                            url: config.base_server() + 'departments/tree?access_token=' + config.getToken().access_token,
                            // 访问数据接口参数
                            param: {companyId: item.value, parentId: '0'},
                        });

                        $('#zt_select').lrselectRefresh({
                            // 访问数据接口地址
                            url: config.base_server() + 'gzzts/dropdownlist?access_token=' + config.getToken().access_token,
                            // 访问数据接口参数
                            param: {companyId: companyId, showcheck: "1"},
                            select: function (ztItem) {
                                if (!ztItem || ztItem.value == '-1') {

                                } else {
                                    // page.initHeader();
                                    // page.search();
                                }
                            }
                        });
                    }
                }
            });
            $('#company_select').lrselectRefresh({
                // 访问数据接口地址
                url: config.base_server() + 'companys/tree?access_token=' + config.getToken().access_token,
                // 访问数据接口参数
                param: {parentId: '0'}
            }).lrselectSet(userdefault.companyId);
            // 帐套选择
            $('#zt_select').lrselect({
                type: 'multiple',
                placeholder: '请选择帐套',
                // 展开最大高度
                maxHeight: 380,
                allowSearch: true
            });
            // 部门选择
            $('#departmentName').lrselect({
                type: 'multiple',
                placeholder: '部门',
                title: 'text',
                text: 'text',
                value: 'text',
                // 是否允许搜索
                allowSearch: true,
                select: function (item) {
                    if (item && item.value != '') {
                        departmentName = item.text;
                    } else {
                        departmentName = '';
                    }
                }
            });
            // 用户类型
            $('#userCategory').lrDataItemSelect({
                code: 'UserCategorys',
                type: 'multiple',
                placeholder: "员工类型",
                allowSearch: true
            });

            // 查询
            $('#btn_Search').on('click', function () {
                var keyword = $('#txt_Keyword').val();

                page.initHeader();
                var _tempHeaderCols = jQuery.extend(true, [], headerCols);

                if (!!selectColumns) {
                    for (var i = 0; i < _tempHeaderCols.length; i++) {
                        if ((_tempHeaderCols[i].name != 'id' && _tempHeaderCols[i].name != 'departmentname' && _tempHeaderCols[i].name != 'usercode' && _tempHeaderCols[i].name != 'username' && _tempHeaderCols[i].name != 'month') &&
                            selectColumns.indexOf(_tempHeaderCols[i].label) < 0
                        ) {
                            _tempHeaderCols.splice(i, 1);
                            i--;
                        }
                    }
                }

                page.initGrid(_tempHeaderCols);
                page.search({keyword: keyword});
            });
            // 刷新
            $('#lr_refresh').on('click', function () {
                location.reload();
            });
            //打印
            $('#lr_print').on('click', function () {
                var ztId = $('#zt_select').lrselectGet();
                if (!ztId) {
                    learun.alert.warning('请选择账套！');
                    return false;
                }

                learun.layerForm({
                    id: 'form_printsetting',
                    title: '打印设置',
                    url: config.webportal_server + 'pages/salary/report/selectColumn.html?companyId=' + companyId + '&ztId=' + ztId + '&access_token=' + config.getToken().access_token,
                    width: 800,
                    height: 520,
                    callBack: function (id) {
                        var configData = top[id].acceptClick();
                        if (configData) {
                            var index = top.layer.getFrameIndex("form_printsetting");
                            top.layer.close(index);
                            page.printview(configData);
                        }
                    }
                });
            });
            //选择列导出
            $('#lr_export_select').on('click', function () {
                var ztId = $('#zt_select').lrselectGet();
                if (!ztId) {
                    learun.alert.warning('请选择账套！');
                    return false;
                }

                learun.layerForm({
                    id: 'form_printsetting',
                    title: '导出工资记录',
                    url: config.webportal_server + 'pages/salary/report/exportColumn.html?companyId=' + companyId + '&ztId=' + ztId + '&access_token=' + config.getToken().access_token,
                    width: 500,
                    height: 520,
                    callBack: function (id) {
                        var configData = top[id].acceptClick();
                        if (configData) {
                            var index = top.layer.getFrameIndex("form_printsetting");
                            top.layer.close(index);

                            params.access_token = config.getToken().access_token;
                            params.columns = configData.columns;
                            learun.download({
                                url: config.base_server() + 'gzreports/gzmxb/exportExcel',
                                param: params,
                                method: 'GET'
                            });

                        }
                    }
                });
            });
            //Excel导出
            $("#lr_export").on('click', function () {
                var ztId = $('#zt_select').lrselectGet();
                if (!ztId) {
                    learun.alert.warning('请选择账套！');
                    return false;
                }
                params.access_token = config.getToken().access_token;
                params.columns = null;
                learun.download({
                    url: config.base_server() + 'gzreports/gzmxb/exportExcel',
                    param: params,
                    method: 'GET'
                });
            });
            //选列查看
            $('#lr_column').on('click', function () {
                var ztId = $('#zt_select').lrselectGet();
                if (!ztId) {
                    learun.alert.warning('请选择账套！');
                    return false;
                }

                learun.layerForm({
                    id: 'form_printsetting',
                    title: '选择款项查看',
                    url: config.webportal_server + 'pages/salary/report/exportColumn.html?companyId=' + companyId + '&ztId=' + ztId + '&access_token=' + config.getToken().access_token,
                    width: 500,
                    height: 520,
                    callBack: function (id) {
                        var configData = top[id].acceptClick();
                        if (configData) {
                            var index = top.layer.getFrameIndex("form_printsetting");
                            top.layer.close(index);

                            params.access_token = config.getToken().access_token;
                            params.columns = configData.columns;
                            selectColumns = configData.columns; //所选列

                            var _tempHeaderCols = jQuery.extend(true, [], headerCols);
                            for (var i = 0; i < _tempHeaderCols.length; i++) {
                                if ((_tempHeaderCols[i].name != 'id' && _tempHeaderCols[i].name != 'departmentname' && _tempHeaderCols[i].name != 'usercode' && _tempHeaderCols[i].name != 'username' && _tempHeaderCols[i].name != 'month') &&
                                    configData.columns.indexOf(_tempHeaderCols[i].label) < 0
                                ) {
                                    _tempHeaderCols.splice(i, 1);
                                    i--;
                                }
                            }

                            page.initGrid(_tempHeaderCols);
                            page.search();
                        }
                    }
                });
            });
        },
        initGrid: function (headData) {
            $('#gridtable').jfGridClear();
            $('#gridtable').jfGrid({
                url: config.base_server() + 'gzreports/gzmxb/listall?access_token=' + config.getToken().access_token,
                headData: headData,
                isPage: false,
                rows: 1000,
                reloadSelected: true,
                mainId: 'code'
            });
        },
        initHeader: function (param) {
            var ztId = $('#zt_select').lrselectGet();
            if (!ztId) {
                learun.alert.warning('请选择账套！');
                return false;
            }
            param = param || {};
            param.companyId = companyId;
            param.ztId = ztId;
            param.editable = "0";
            learun.httpPost2(config.base_server() + 'gzreports/gzmxb/header?access_token=' + config.getToken().access_token, param, function (res) {
                learun.loading(false);
                if (res.resp_code == 200) {
                    colNames = res.data.colNames;
                    colData2 = res.data.colData2;
                    for (var i = 0; i < res.data.colData.length; i++) {
                        if (res.data.colData[i].formatter) {
                            res.data.colData[i].formatter = eval("(function(){return " + res.data.colData[i].formatter + " })()");
                        }
                        if (res.data.colData[i].edit && res.data.colData[i].edit.change) {
                            res.data.colData[i].edit.change = eval("(function(){return " + res.data.colData[i].edit.change + " })()");
                        }
                        if (res.data.colData[i].children) {
                            for (var j = 0; j < res.data.colData[i].children.length; j++) {
                                if (res.data.colData[i].children[j].formatter) {
                                    res.data.colData[i].children[j].formatter = eval("(function(){return " + res.data.colData[i].children[j].formatter + " })()");
                                }
                            }
                        }
                    }
                    headerCols = jQuery.extend(true, [], res.data.colData);
                    page.initGrid(res.data.colData);
                } else {
                    learun.alert.error(res.resp_msg);
                    learun.httpErrorLog(res.resp_msg);
                }
            });
        },
        search: function (param) {
            var keyword = $('#txt_Keyword').val();
            var ztId = $('#zt_select').lrselectGet();
            if (!ztId) {
                return false;
            }
            param = param || {};
            param.companyId = companyId;
            param.ztId = ztId;
            param.monthStart = $("#monthStart").val();
            param.monthEnd = $("#monthEnd").val();

            var departmentName = $('#departmentName').lrselectGet();
            var userCategory = $('#userCategory').lrselectGet();
            param.departmentName = departmentName;
            param.userCategory = userCategory;
            param.keyword = keyword;

            params = param;

            $('#gridtable').jfGridSet('reload', param);
        },
        printview: function (param) {
            learun.loading(true, '数据加载中...');
            var hiprintTemplate = null;
            learun.httpAsyncGet2(config.base_server() + 'printTempletes/findByCode', "&code=" + param.printTemplateCode, function (res) {
                var tempHeader = $.extend(true, [], colData2);
                if (res.resp_code == 200) {
                    var cols = ("部门,姓名," + param.columns).split(",");
                    for (var i = 0; i < tempHeader.length; i++) {
                        var flag = false;
                        for (var j = 0; j < cols.length; j++) {
                            if (cols[j] == tempHeader[i].title) {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag) {
                            tempHeader.splice(i, 1);
                            i--;
                        }
                    }

                    var temp = JSON.parse(res.data.templete);
                    temp.panels[0].printElements[3].options.columns[0] = tempHeader;
                    var temp2 = JSON.stringify(temp);
                    var temp3 = JSON.parse(temp2);

                    hiprintTemplate = new hiprint.PrintTemplate({
                        template: temp3,
                        paginationContainer: '.hiprint-printPagination'
                    });

                    params.ignoreUsername = param.ignoreUsername;
                    $.ajax({
                        url: config.base_server() + 'gzreports/gzmxb/listall?access_token=' + config.getToken().access_token,
                        data: params,
                        type: 'GET',
                        dataType: "json",
                        success: function (resData) {

                            var ztId = $('#zt_select').lrselectGet();


                            var item = {};
                            item.pzflList = [];

                            var totalRow = {};
                            for (var i = 0; i < resData.data.length; i++) {
                                if (ztId == 'd023aac4077b460a938a43ea41823f2a') {//陪审员
                                    if (param.hideZero == 1 && !resData.data[i]['陪审员补助']) {

                                    } else {
                                        item.pzflList.push(resData.data[i]);
                                    }
                                } else if (ztId == '4b4fe1f21b3d4671b5f01ad651eabf21') {//调解员
                                    if (param.hideZero == 1 && !resData.data[i]['调解员补助']) {

                                    } else {
                                        item.pzflList.push(resData.data[i]);
                                    }
                                } else if (ztId == '5001182d7c9f4328974de6211194174a') {//心里疏导员
                                    if (param.hideZero == 1 && !resData.data[i]['心理疏导员补助']) {

                                    } else {
                                        item.pzflList.push(resData.data[i]);
                                    }
                                } else if (ztId == 'fb27b8bf0b544c0481c83cb6ca0e3c4f') {//行政编
                                    if (param.hideZero == 1 && !resData.data[i]['实发住补']) {

                                    } else {
                                        item.pzflList.push(resData.data[i]);
                                    }
                                } else {
                                    item.pzflList.push(resData.data[i]);
                                }
                            }
                            for (var i = 0; i < item.pzflList.length; i++) {
                                jQuery.each(item.pzflList[i], function (key, val) {
                                    if (!(key == 'departmentid' || key == 'departmentname' || key == 'userid' || key == 'usercode' || key == 'username' || key == 'month')) {
                                        totalRow[key] = (totalRow[key] == undefined ? 0.00 : totalRow[key]) + val;
                                        item.pzflList[i][key] = $.formatMoney(val, 2);
                                    }
                                });
                            }
                            totalRow.departmentname = "合计："
                            totalRow.username = item.pzflList.length + "人"
                            jQuery.each(totalRow, function (key, val) {
                                if (!(key == 'departmentid' || key == 'departmentname' || key == 'userid' || key == 'usercode' || key == 'username' || key == 'month')) {
                                    totalRow[key] = $.formatMoney(val, 2);
                                }
                            });
                            item.pzflList[item.pzflList.length] = totalRow;

                            // item.title = "2021年9月工资表";
                            item.title = param.title;
                            item.ztName = $("#company_select .lr-select-placeholder").html();
                            var y = new Date().getFullYear();
                            var m = new Date().getMonth() + 1;
                            if (m < 10) {
                                m = '0' + m;
                            }
                            var d = new Date().getDate();
                            var pzrq = y + "-" + m + "-" + d;
                            item.pzrq = pzrq;
                            //hiprintTemplate.print(item);

                            hiprintTemplate.resetPage();
                            $('#myModal .modal-body .prevViewDiv').html(hiprintTemplate.getHtml(item));
                            $('#myModal').modal('show');
                            learun.loading(false);
                        }
                    });
                }
            });
            $('#A4_printByHtml').click(function () {
                hiprintTemplate.printByHtml($('#myModal .modal-body .prevViewDiv'));
            })
        }
    };

    // 保存数据后回调刷新
    refreshGirdData = function () {
        page.search();
    };

    page.init();
}


